'use strict';
const axios = require('axios');

// 小红书API配置
const XIAOHONGSHU_API = {
    // 这里需要填写小红书开放平台的配置信息
    appKey: 'your_app_key',
    appSecret: 'your_app_secret',
    baseUrl: 'https://api.xiaohongshu.com'
};

exports.main = async (event, context) => {
    try {
        const { userId, note } = event;

        // 1. 获取用户的小红书授权信息
        const userAuth = await getUserAuth(userId);

        // 2. 上传图片到小红书
        const imageUrls = await Promise.all(
            note.images.map(img => uploadImage(img, userAuth.accessToken))
        );

        // 3. 发布笔记
        const response = await axios.post(
            `${XIAOHONGSHU_API.baseUrl}/content/publish`,
            {
                title: note.title,
                content: note.content,
                images: imageUrls,
                type: 'normal' // 普通笔记类型
            },
            {
                headers: {
                    'Authorization': `Bearer ${userAuth.accessToken}`,
                    'Content-Type': 'application/json'
                }
            }
        );

        return {
            code: 0,
            message: '发布成功',
            data: response.data
        };
    } catch (error) {
        console.error('发布失败:', error);
        return {
            code: -1,
            message: error.message || '发布失败',
            data: null
        };
    }
};

// 获取用户的小红书授权信息
async function getUserAuth(userId) {
    const db = uniCloud.database();
    const userCollection = db.collection('users');

    const user = await userCollection.doc(userId).get();
    if (!user.data || !user.data[0].xiaohongshuAuth) {
        throw new Error('请先绑定小红书账号');
    }

    return user.data[0].xiaohongshuAuth;
}

// 上传图片到小红书
async function uploadImage(imageUrl, accessToken) {
    // 1. 从云存储下载图片
    const imageFile = await uniCloud.downloadFile({
        fileID: imageUrl
    });

    // 2. 获取上传凭证
    const uploadAuth = await axios.get(
        `${XIAOHONGSHU_API.baseUrl}/content/upload/auth`,
        {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        }
    );

    // 3. 上传图片
    const formData = new FormData();
    formData.append('file', imageFile);

    const uploadResult = await axios.post(
        uploadAuth.data.uploadUrl,
        formData,
        {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
    );

    return uploadResult.data.url;
} 